// manager/pages/customerall/index.js
import config from '../../../utils/config';
import { request } from '../../../utils/request';
import util from '../../../common/util';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: config.baseUrl,
        userInfo: {},
        type: "", // 1自己，2全部
        subActiveValue: "",
        subTab: [],

        showFilter: false,
        params: {
            search: "",
            perType: "", // 个人客户类型
            areaName: "", // 网格名称       
            industry: "",
            locationName: "",
            agrType: "", // 农业主体类型
            agrLicenseName: "", // 营业执照名称
        },
        filterTypeIndex: 0,
        personFilterTypes: [
            { id: 1, text: '展示个人列表' },
            { id: 2, text: '展示网格列表' },
        ],
        filterTypes: [
            { id: 1, text: '展示企业列表' },
            { id: 2, text: '展示楼宇列表' },
        ],
        isFilter: false,
        // 客户字典
        typeList: [],
        typeIndex: -1,
        // 个人类型
        personTypeList: [],
        personTypeIndex: -1,
        // 行业字典
        merchantIndustryList: [],
        enterpriseIndustryList: [],
        industryIndex: -1,
        // 新型农业主体类型
        agricultureTypeList: [],
        agricultureTypeIndex: -1,
        scroller: {
			pageNum: 0,
			pageSize: 10,
			totalPage: 10,
			isNoneLoading: true,
			refreshColor: '#000000',
			refreshDiy: false,
			isloaded: false,
			list: []
        },
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        
        this.getDictionaryInfo("ecard_person_type");
        this.getDictionaryInfo("ecard_merchant_industry");
        this.getDictionaryInfo("ecard_enterprise_industry");
        this.getDictionaryInfo("ecard_agriculture_type");

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getUserInfo();
    },
    // 获取当前登录者的用户信息
    getUserInfo(e) {        
        request({
            url: "/user/getUserInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {}
        }).then(res => {
            if(res.code == 0){
                let { userInfo } = this.data;
                let postCodeArr = userInfo.extendPostCode?userInfo.extendPostCode.split(","):[];
                this.setData({
                    userInfo: res.data.userInfo,
                    type: postCodeArr.indexOf("wg") != -1 ? 2 : 1
                })
                this.getDictionaryInfo("ecard_cust_type");
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取字典
     */
    getDictionaryInfo(dictType) {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
                dictType
            }
        }).then(res => {
            if(res.code == 0){
                if(dictType == 'ecard_cust_type'){
                    let subTab = [];
                    let typeList = [
                        {
                            dictLabel: "全部",
                            dictValue: ""
                        }
                    ];
                    subTab = res.data;
                    this.setData({
                        subActiveValue: subTab[0] ? subTab[0].dictValue: "",
                        subTab,
                        typeList: typeList.concat(subTab)
                    })
                    this.resetData();
                    this.getData();
                }
                if(dictType == 'ecard_person_type'){
                    let personTypeList = [
                        {
                            dictLabel: "全部",
                            dictValue: ""
                        }
                    ];
                    this.setData({
                        personTypeList: personTypeList.concat(res.data)
                    })
                }
                if(dictType == 'ecard_merchant_industry'){
                    let merchantIndustryList = [];
                    merchantIndustryList.push({
                        dictLabel: "全部",
                        dictValue: ""
                    })
                    this.setData({
                        merchantIndustryList: merchantIndustryList.concat(res.data)
                    })
                }
                if(dictType == 'ecard_enterprise_industry'){
                    let enterpriseIndustryList = [];
                    enterpriseIndustryList.push({
                        dictLabel: "全部",
                        dictValue: ""
                    })
                    this.setData({
                        enterpriseIndustryList: enterpriseIndustryList.concat(res.data)
                    })
                }
                if(dictType == 'ecard_agriculture_type'){
                    let agricultureTypeList = [];
                    agricultureTypeList.push({
                        dictLabel: "全部",
                        dictValue: ""
                    })
                    this.setData({
                        agricultureTypeList: agricultureTypeList.concat(res.data)
                    })
                }
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 重置数据
     */
    resetData(){
		this.resetParams();
		this.resetScroller();
    },
    /**
     * 重置下拉
     */
    resetScroller(){
        let scroller = {
			pageNum: 0,
			pageSize: 10,
			totalPage: 10,
			isNoneLoading: true,
			refreshColor: '#000000',
			refreshDiy: false,
			isloaded: false,
			list: []
		}
		this.setData({
            scroller,
		})
    },
    /**
     * 验证params是否有值
     */
    validateParams(){
        let isFilter = false;
        let { params } = this.data;
        for(let key in params){
            console.log(params[key])
            if(params[key]){
                isFilter = true;
            }
        }
        this.setData({
            isFilter
		})
    },
    /**
     * 重置参数
     */
    resetParams(){
        let { params } = this.data;
        Object.keys(params).forEach((key) => (params[key] = ''))
		this.setData({
            params,
            industryIndex: -1,
            personTypeIndex: -1,
            typeIndex: -1,
            agricultureTypeIndex: -1,
            isFilter: false
		})
    },
    /** 分类点击事件*/
    subTabChange(e) {
        let { value } = e.currentTarget.dataset;
        this.setData({
            subActiveValue: value
        })
        this.resetData()
        this.getData();
    },
    /**
     * 显示筛选
     */
    showFilterPopup(){
        this.setData({
            showFilter: true
        })
    },
    /**
     * 关闭筛选
     */
    closeFilter(){
        this.setData({
            showFilter: false
        })
    },
    /**
     * 分类筛选
     */
    filterTypeChange(e){
        let { index } = e.currentTarget.dataset;
        this.setData({
            filterTypeIndex: index
        })
        this.resetScroller();
        this.getData();
    },
    /**
     * 确认筛选
     */
    confirmFilter(){
        this.setData({
            showFilter: false
        })
        this.validateParams();
        this.resetScroller();
        this.getData();
    },
    
    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['params.'+key]: e.detail.value,
            // isFilter: !!e.detail.value,
        })
    },
    // 搜索
    searchConfirm(e){
        let key = e.currentTarget.dataset.key;
        this.setData({
            ['params.'+key]: e.detail.value,
            showFilter: false
        })
        this.validateParams();
        // 页面加载时执行一次加载
		this.resetScroller()
        this.getData();
    },
    searchBtn(e){
        this.resetScroller()
        this.getData();
    },
    bindTypeChange(e){
        this.setData({
            typeIndex: e.detail.value,
            industryIndex: -1,
            'params.industry': ""
        })
    },
    bindPersonTypeChange(e){
        this.setData({
            personTypeIndex: e.detail.value,
            'params.perType': this.data.personTypeList[e.detail.value].dictValue
        })
    },
    bindMerchantIndustryChange(e){
        this.setData({
            industryIndex: e.detail.value,
            'params.industry': this.data.merchantIndustryList[e.detail.value].dictValue
        })
    },
    bindEnterpriseIndustryChange(e){
        this.setData({
            industryIndex: e.detail.value,
            'params.industry': this.data.enterpriseIndustryList[e.detail.value].dictValue
        })
    },
    bindAgricultureTypeChange(e){
        this.setData({
            agricultureTypeIndex: e.detail.value,
            'params.agrType': this.data.agricultureTypeList[e.detail.value].dictValue
        })
    },
    /**
     * 获取数据
     */
    getData() {
        let { subActiveValue, filterTypeIndex } = this.data;
        switch(subActiveValue){
            case '1':
                // 个人列表
                if(filterTypeIndex == 0){
                    this.getPersonList()
                }
                // 网格列表
                if(filterTypeIndex == 1){
                    this.getAllPersonAreaInfoList()
                }
                break;
            case '2':
                this.getMerchantList()
                break;
            case '3':
                // 企业列表
                if(filterTypeIndex == 0){
                    this.getEnterpriseList()
                }
                // 楼宇列表
                if(filterTypeIndex == 1){
                    this.getAllLocationInfoList()
                }
                break;
            case '4':
                this.getAgricultureList()
                break;
            default: 
                break;
        }
    },

    /**
     * 获取全部个人
     */
    getPersonList() {
		let { scroller } = this.data;
        scroller.pageNum = scroller.pageNum + 1;
        if(scroller.pageNum>scroller.totalPage){
            return
        }
        request({
            url: `/personMarketing/getPersonList`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                ...this.data.params,
                type: this.data.type,
                pageNum: this.data.scroller.pageNum,
                pageSize: this.data.scroller.pageSize,
            }
        }).then(res => {
            if(res.code == 0){
                scroller.totalPage = Math.ceil(res.total/scroller.pageSize);
                if(scroller.pageNum>=scroller.totalPage){
                    scroller.isNoneLoading = false;
                }
                if(res.data.length>0){
                    res.data.map(item => {
                        item.creationTime = util.formatTime(new Date(item.creationTime));
                        item.lastVisitDate = item.lastVisitDate?util.formatTime(new Date(item.lastVisitDate)):"";
                        return item
                    })
                }
                if(scroller.pageNum == 1){
                    scroller.list = res.data;
                }else{
                    scroller.list = scroller.list.concat(res.data);
                }
                this.setData({
                    scroller
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取全部网格
     */
    getAllPersonAreaInfoList() {
		let { scroller } = this.data;
        scroller.pageNum = scroller.pageNum + 1;
        if(scroller.pageNum>scroller.totalPage){
            return
        }
        request({
            url: `/personMarketing/getAllPersonAreaInfoList`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                ...this.data.params,
                type: this.data.type,
                pageNum: this.data.scroller.pageNum,
                pageSize: this.data.scroller.pageSize,
            }
        }).then(res => {
            if(res.code == 0){
                scroller.totalPage = Math.ceil(res.total/scroller.pageSize);
                if(scroller.pageNum>=scroller.totalPage){
                    scroller.isNoneLoading = false;
                }
                if(res.data.length>0){
                    res.data.map(item => {
                        item.creationTime = util.formatTime(new Date(item.creationTime));
                        item.lastVisitDate = item.lastVisitDate?util.formatTime(new Date(item.lastVisitDate)):"";
                        return item
                    })
                }
                if(scroller.pageNum == 1){
                    scroller.list = res.data;
                }else{
                    scroller.list = scroller.list.concat(res.data);
                }
                this.setData({
                    scroller
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取全部商户
     */
    getMerchantList() {
		let { scroller } = this.data;
        scroller.pageNum = scroller.pageNum + 1;
        if(scroller.pageNum>scroller.totalPage){
            return
        }
        request({
            url: `/merchantMarketing/getMerchantList`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                ...this.data.params,
                type: this.data.type,
                pageNum: this.data.scroller.pageNum,
                pageSize: this.data.scroller.pageSize,
            }
        }).then(res => {
            if(res.code == 0){
                scroller.totalPage = Math.ceil(res.total/scroller.pageSize);
                if(scroller.pageNum>=scroller.totalPage){
                    scroller.isNoneLoading = false;
                }
                if(res.data.length>0){
                    res.data.map(item => {
                        item.creationTime = util.formatTime(new Date(item.creationTime));
                        item.lastVisitDate = item.lastVisitDate?util.formatTime(new Date(item.lastVisitDate)):"";
                        return item
                    })
                }
                if(scroller.pageNum == 1){
                    scroller.list = res.data;
                }else{
                    scroller.list = scroller.list.concat(res.data);
                }
                this.setData({
                    scroller
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取全部企业
     */
    getEnterpriseList() {
		let { scroller } = this.data;
        scroller.pageNum = scroller.pageNum + 1;
        if(scroller.pageNum>scroller.totalPage){
            return
        }
        request({
            url: `/enterpriseMarketing/getEnterpriseList`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                ...this.data.params,
                type: this.data.type,
                pageNum: this.data.scroller.pageNum,
                pageSize: this.data.scroller.pageSize,
            }
        }).then(res => {
            if(res.code == 0){
                console.log(res)
                scroller.totalPage = Math.ceil(res.total/scroller.pageSize);
                if(scroller.pageNum>=scroller.totalPage){
                    scroller.isNoneLoading = false;
                }
                if(res.data.length>0){
                    res.data.map(item => {
                        item.creationTime = util.formatTime(new Date(item.creationTime));
                        item.lastVisitDate = item.lastVisitDate?util.formatTime(new Date(item.lastVisitDate)):"";
                        return item
                    })
                }
                if(scroller.pageNum == 1){
                    scroller.list = res.data;
                }else{
                    scroller.list = scroller.list.concat(res.data);
                }
                this.setData({
                    scroller
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取全部楼宇
     */
    getAllLocationInfoList() {
		let { scroller } = this.data;
        scroller.pageNum = scroller.pageNum + 1;
        if(scroller.pageNum>scroller.totalPage){
            return
        }
        request({
            url: `/enterpriseMarketing/getAllLocationInfoList`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                ...this.data.params,
                type: this.data.type,
                locationType: 1,
                pageNum: this.data.scroller.pageNum,
                pageSize: this.data.scroller.pageSize,
            }
        }).then(res => {
            if(res.code == 0){
                console.log(res)
                scroller.totalPage = Math.ceil(res.total/scroller.pageSize);
                if(scroller.pageNum>=scroller.totalPage){
                    scroller.isNoneLoading = false;
                }
                if(res.data.length>0){
                    res.data.map(item => {
                        item.creationTime = util.formatTime(new Date(item.creationTime));
                        item.lastVisitDate = item.lastVisitDate?util.formatTime(new Date(item.lastVisitDate)):"";
                        return item
                    })
                }
                if(scroller.pageNum == 1){
                    scroller.list = res.data;
                }else{
                    scroller.list = scroller.list.concat(res.data);
                }
                this.setData({
                    scroller
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取全部新型农业主体
     */
    getAgricultureList() {
		let { scroller } = this.data;
        scroller.pageNum = scroller.pageNum + 1;
        if(scroller.pageNum>scroller.totalPage){
            return
        }
        request({
            url: `/agricultureMarketing/getAgricultureList`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                ...this.data.params,
                type: this.data.type,
                pageNum: this.data.scroller.pageNum,
                pageSize: this.data.scroller.pageSize,
            }
        }).then(res => {
            if(res.code == 0){
                console.log(res)
                scroller.totalPage = Math.ceil(res.total/scroller.pageSize);
                if(scroller.pageNum>=scroller.totalPage){
                    scroller.isNoneLoading = false;
                }
                if(res.data.length>0){
                    res.data.map(item => {
                        item.creationTime = util.formatTime(new Date(item.creationTime));
                        item.lastVisitDate = item.lastVisitDate?util.formatTime(new Date(item.lastVisitDate)):"";
                        return item
                    })
                }
                if(scroller.pageNum == 1){
                    scroller.list = res.data;
                }else{
                    scroller.list = scroller.list.concat(res.data);
                }
                this.setData({
                    scroller
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    
	refresh() {
        this.resetData()
        this.getData()
    },
    
	loadMore() {
        console.log("loadMore")
		this.getData()
    },
    /**
     * 跳转不可编辑楼宇企业
     */
    toGridbuildingdesc(e) {
        let { id, name, type } = e.currentTarget.dataset;
        wx.navigateTo({
          url: `/manager/pages/gridbuildingdesc/index?id=${id}&name=${name}&merchantType=${type}`,
        })
    },

    /**
     * 跳转不可编辑拜访记录
     */
    toGridvisit(e) {
        let { id, type } = e.currentTarget.dataset;
        wx.navigateTo({
          url: `/manager/pages/gridvisit/index?merchantId=${id}&merchantType=${type}`,
        })
    },  
    /**
     * 跳转不可编辑网格
     */
    toGridareadesc(e) {
        let { id, name, type } = e.currentTarget.dataset;
        wx.navigateTo({
          url: `/manager/pages/gridareadesc/index?id=${id}&name=${name}&merchantType=${type}`,
        })
    },

    // 查看图片
    previewImage(e) {
        let { url } = e.currentTarget.dataset;
        if(url){
            wx.previewImage({
                current: url, // 当前显示图片的http链接
                urls: [url] // 需要预览的图片http链接列表
            })
        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },
})